package controllers;

import dao.IUserDao;
import models.User;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.With;
import serviceImpl.UserDaoImpl;

/**
 * 用户操作类
 * Created by 国彬 on 2016/7/2.
 */
public class UserAction extends Controller {

    static IUserDao userDao = new UserDaoImpl();
    @Before(unless = {"loginPage","registerPage"})
    static void checkLogin(){
        renderArgs.put("cxt",request.host);
        if(session.get("user")!=null){
            renderArgs.put("user",User.findById(session.get("user")));
        }
    }

    public static void loginPage(){
        render("Application/login.html");
    }
    public static void registerPage(){
        render("Application/register.html");
    }
    /**
     * 用户注册，post
     */
    public static void register(){
        String name = request.params.get("reg_username");
        String province = request.params.get("reg_province");
        String city = request.params.get("reg_city");
        String phone = request.params.get("reg_phone");
        String password = request.params.get("reg_password");
        String area = request.params.get("reg_area");
        User user = new User();
        user.name = name;
        user.province = province;
        user.phone = phone;
        user.city = city;
        user.password = password;
        user.area = area;

        if (userDao.findByPhone(phone)>0) {
            WebService.wsError("user exists");
        } else {
            user.save();
            session.put("user",user.id);
           redirect("Application.index");
        }
    }

    /**
     * 检查该号码是否被注册
     */
    public static void checkPhone(){
        String phone = request.params.get("reg_phone");
        if(userDao.findByPhone(phone)>0){
            controllers.WebService.wsError("user exist");
        }else{
            WebService.wsOk("success");
        }
    }

    /**
     * 登录
     */
    public static void login(){
        String phone = request.params.get("login_phone");
        String password = request.params.get("login_password");
        User user = userDao.findByPhoneAndPwd(phone,password);
        if(user!=null){
            session.put("user",user.id);
            redirect("Application.index");
            //render("Application/home.html");
        }else{
            WebService.wsError("用户不存在或密码错误");
        }

    }
}
